// 腾讯地图WebService API密钥
const TENCENT_MAP_KEY = '6WABZ-6Z2CV-LJ6PQ-5U26D-HV2C5-2PBYI';
// 腾讯地图逆地理编码API地址
const REVERSE_GEOCODING_URL = "https://apis.map.qq.com/ws/geocoder/v1/";

/**
 * 检查定位权限并请求授权
 * @returns {Promise<boolean>} 是否获得权限
 */
function checkLocationPermission() {
  return new Promise((resolve) => {
    // #ifdef APP-PLUS
    // APP环境下检查权限
    if (plus.os.name === 'Android') {
      // 安卓设备权限检查
      const permission = 'android.permission.ACCESS_FINE_LOCATION';
      plus.android.requestPermissions([permission], (result) => {
        resolve(result.granted.length > 0);
      }, (error) => {
        console.log('权限请求失败:', error);
        resolve(false);
      });
    } else {
      // 其他平台
      resolve(true);
    }
    // #endif

    // #ifndef APP-PLUS
    // 非APP环境下的权限检查
    uni.getSetting({
      success: (res) => {
        if (res.authSetting["scope.userLocation"]) {
          resolve(true);
        } else {
          uni.authorize({
            scope: "scope.userLocation",
            success: () => resolve(true),
            fail: () => resolve(false)
          });
        }
      },
      fail: () => resolve(false)
    });
    // #endif
  });
}

/**
 * 获取当前位置信息（经纬度+详细地址）
 * @param {Function} callback 回调函数，接收结果对象
 */
function getLocationInfo(callback) {
  console.log('开始获取位置信息...');

  // 检查是否为安卓设备
  let isAndroid = false;
  // #ifdef APP-PLUS
  isAndroid = plus.os.name === 'Android';
  // #endif

  // #ifndef APP-PLUS
  try {
    const systemInfo = uni.getSystemInfoSync();
    isAndroid = systemInfo.platform === 'android';
  } catch (e) {
    console.log('获取系统信息失败:', e);
  }
  // #endif

  console.log('当前设备类型:', isAndroid ? 'Android' : '其他');

  // 步骤1：检查权限
  checkLocationPermission().then((hasPermission) => {
    console.log('权限检查结果:', hasPermission);

    if (!hasPermission) {
      const message = "请在设置中开启位置权限";
      console.log(message);
      callback({
        success: false,
        message: message
      });
      return;
    }

    // 步骤2：获取经纬度
    console.log('开始获取经纬度...');
    uni.getLocation({
      type: "wgs84",
      altitude: false,
      success: (locationRes) => {
        console.log('获取经纬度成功:', locationRes);

        const {
          latitude,
          longitude
        } = locationRes;

        // 在安卓设备上打印经纬度信息
        if (isAndroid) {
          console.log('=== 当前位置信息 ===');
          console.log(`纬度: ${latitude.toFixed(6)}`);
          console.log(`经度: ${longitude.toFixed(6)}`);
          console.log('==================');
        }

        // 步骤3：调用腾讯地图逆地理编码API
        console.log('开始解析地址信息...');
        uni.request({
          url: REVERSE_GEOCODING_URL,
          method: "GET",
          data: {
            location: `${latitude},${longitude}`,
            key: TENCENT_MAP_KEY,
            get_poi: 0,
            output: "json"
          },
          success: (res) => {
            console.log('地址解析API响应:', res);

            if (res.statusCode === 200 && res.data.status === 0) {
              const result = res.data.result;

              // 在安卓设备上打印详细位置信息
              if (isAndroid) {
                console.log('=== 详细位置信息 ===');
                console.log(`城市: ${result.address_component.city || "未知城市"}`);
                console.log(`区域: ${result.address_component.district || "未知区域"}`);
                console.log(`街道: ${result.address_component.street || "未知街道"}`);
                console.log(`详细地址: ${result.address || "未知地址"}`);
                console.log(`推荐地址: ${result.formatted_addresses.recommend || ""}`);
                console.log('==================');
              }

              // 整理位置信息
              const locationData = {
                success: true,
                data: {
                  latitude: latitude.toFixed(6),
                  longitude: longitude.toFixed(6),
                  city: result.address_component.city || "未知城市",
                  district: result.address_component.district || "未知区域",
                  street: result.address_component.street || "未知街道",
                  address: result.address || "未知地址",
                  formattedAddress: result.formatted_addresses.recommend || ""
                }
              };

              console.log('位置信息获取完成:', locationData);
              callback(locationData);
            } else {
              const message = `地址解析失败：${res.data.message || "未知错误"}`;
              console.log(message);
              callback({
                success: false,
                message: message
              });
            }
          },
          fail: (err) => {
            console.log('地址解析请求失败:', err);
            callback({
              success: false,
              message: `网络请求失败：${err.errMsg}`
            });
          }
        });
      },
      fail: (err) => {
        console.log('获取经纬度失败:', err);
        callback({
          success: false,
          message: `获取经纬度失败：${err.errMsg}`
        });
      }
    });
  });
}

// 导出核心函数
export {
  getLocationInfo
};